import { Hono } from 'hono'
import { auth } from '../lib/auth'
import { prettyJSON } from 'hono/pretty-json'
import { trimTrailingSlash } from 'hono/trailing-slash'

import { logger } from 'hono/logger'
import { cors } from 'hono/cors'
import { contextStorage, getContext } from 'hono/context-storage'

import todoRouter from './routes/todo'
import tags from './routes/tag'
// import { defineEventHandler, toWebRequest } from "h3";
// export const runtime = "nodejs";

export type Env = {
  Variables: {
    user: typeof auth.$Infer.Session.user | null
    session: typeof auth.$Infer.Session.session | null
  }
}

const app = new Hono<Env>().basePath('/api')
app.use(contextStorage()) // 上下文
app.use(trimTrailingSlash()) // 去除尾部斜杠
app.use(prettyJSON()) // 美化json
app.use(logger()) // 日志

const config = useRuntimeConfig()

app.use(
  '*',
  cors({
    origin: [config.BETTER_AUTH_URL || ''], // This is a must. URL where your vue app is running.
    allowHeaders: ['Content-Type', 'Authorization'],
    allowMethods: ['POST', 'GET', 'OPTIONS'],
    exposeHeaders: ['Content-Length'],
    maxAge: 600,
    credentials: true
  })
)

app.use('*', async (c, next) => {
  const session = await auth.api.getSession({ headers: c.req.raw.headers })
  if (!session) {
    c.set('user', null)
    c.set('session', null)
    return next()
  }

  c.set('user', session.user)
  c.set('session', session.session)
  return next()
})

app.on(['POST', 'GET'], '/auth/**', c => auth.handler(c.req.raw))

app.post('/user/restpasswd', async (c) => {
  const { userid, password } = await c.req.json()
  console.log(userid, password)
  const ctx = await auth.$context
  const hash = await ctx.password.hash(password)
  await ctx.internalAdapter.updatePassword(userid, hash)
  return c.json({
    ok: true,
    data: '成功'
  })
})

/**
 * 获取环境上下文信息的函数
 * 该函数通过泛型参数指定环境类型
 * @returns 返回类型为Env的环境上下文信息
 */
export const getContextInfo = () => {
  return getContext<Env>() // 调用泛型函数getContext，并指定Env类型作为参数
}

app.route('/todo', todoRouter)
app.route('/tag', tags)

export default defineEventHandler((event) => {
  return app.fetch(toWebRequest(event))
})

// export type AppType = typeof _routes;
